package org.dfl.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.dfl.log.Logger;

/**
 *
 * @author Lukas
 */
public class Directory {

    private File file;

    protected Directory(String name) {
        file = new File(Repository.getInstance().getHomeFile(), name);
        init();
    }

    protected Directory(Directory parent, String name) {
        file = new File(parent.getFile(), name);
        init();
    }

    private void init() {
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public File getFile() {
        return file;
    }

    public File getStoredFile(String name) {
        File f = new File(getFile(), name);
        if (f.exists()) {
            return f;
        }

        return null;
    }

    public String storeFile(String name, InputStream stream) {
        File f = new File(getFile(), name);

        try {
            FileOutputStream out = new FileOutputStream(f);

            for (;;) {
                byte[] buf = new byte[10240];
                int read = stream.read(buf);
                if (read == -1) {
                    break;
                }

                out.write(buf, 0, read);
            }

            out.close();

            return f.getAbsolutePath();
        } catch (IOException ex) {
            Logger.logException(ex);
            f.delete();
            return null;
        }
    }
}
